package com.student.manager.servlet;

import com.student.manager.bean.Student;
import com.student.manager.service.StudentService;
import com.student.manager.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        try {
            String sname = request.getParameter("sname");
            String gender = request.getParameter("gender");
            String phone = request.getParameter("phone");
            String birthday = request.getParameter("birthday");
            String info = request.getParameter("info");
            String h[] = request.getParameterValues("hobby");

            String hobby = Arrays.toString(h);
            hobby = hobby.substring(1, hobby.length()-1);

            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);

            Student student = new Student(sname, gender, phone, hobby, info, date);

            System.out.println(student);

            StudentService service = new StudentServiceImpl();
            service.insert(student);

            request.getRequestDispatcher("StudentListServlet").forward(request, response);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
